package com.tiance.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.ActivityDO;
import com.tiance.dal.dataobject.PersonMessageDO;
import com.tiance.dal.dataobject.PublishInfoDO;
import com.tiance.domainservice.checker.ActivityChecker;
import com.tiance.domainservice.checker.PublishInfoChecker;
import com.tiance.domainservice.domain.ActivityDomain;
import com.tiance.domainservice.domain.PublishInfoDomain;
import com.tiance.domainservice.service.ActivityService;
import com.tiance.domainservice.service.PublishInfoService;
import com.tiance.enums.ApplicantTypeEnum;
import com.tiance.enums.EntityTypeEnum;
import com.tiance.enums.OperateTypeEnum;
import com.tiance.enums.PublishInfoStatusEnum;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.page.QueryPage;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.utils.DateUtils;
import com.tiance.vo.ActivityVO;
import com.tiance.vo.PersonMessageVO;
import com.tiance.vo.PublishInfoVO;
import com.tiance.vo.SignInVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：发布信息管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/front/publishInfo")
public class PublishInfoController extends FrontController{

    private static String LOG_PREFIX ="PublishInfoController| 发布信息控制器===>";

    @Autowired
    private PublishInfoService publishInfoService;


    @RequestMapping(value = "/toAppinforrelease.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到申请发布信息页面")
    public String toAppinforrelease(Model model) {
        model.addAttribute("publishInfoVO",new PublishInfoVO());
        return "/front/appinforrelease";

    }


    @RequestMapping(value = "/toPubmessage.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到活动申请页面")
    public String toPubmessage(Model model) {
        model.addAttribute("publishInfoVO",new PublishInfoVO());
        return "/front/pubmessage";

    }

    @RequestMapping(value = "/addPublishInfo.action",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="插入发布信息")
    public String addPublishInfo( HttpServletRequest request,Model model,PublishInfoVO publishInfoVO){
        logger.info("开始插入发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                publishInfoVO.setApplicantId((Long)memberId);
            }
            PublishInfoChecker.addPublishInfo(publishInfoVO);
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            publishInfoDomain.setApplicantType(ApplicantTypeEnum.MEMBER.getCode());
            publishInfoService.addPublishInfo(publishInfoDomain);
            model.addAttribute("publishInfoVO",publishInfoVO);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"插入发布信息失败，失败原因：",e1);
            publishInfoVO.setErrorInfo(e1.getMessage());
            model.addAttribute("publishInfoVO",publishInfoVO);
            return "/front/appinforrelease";

        }catch (Exception e2){
            logger.error(LOG_PREFIX+"插入发布信息失败,失败原因",e2);
            publishInfoVO.setErrorInfo("发布失败，请稍后再试");
            model.addAttribute("publishInfoVO",publishInfoVO);
            return "/front/appinforrelease";
        }
        logger.info("结束插入发布信息，返回数据:{}", JSON.toJSONString(publishInfoVO));
        return  "/front/pubmessage";

    }


    @RequestMapping(value = "/cancel.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="取消发布信息")
    public BaseResponse cancel( HttpServletRequest request,PublishInfoVO publishInfoVO){
        logger.info("开始取消发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoVO> response=new BaseResponse();

        try {
            PublishInfoChecker.checkId(publishInfoVO.getId());
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            publishInfoDomain.setInfoStatus(PublishInfoStatusEnum.INFO_CANCEL.getCode());
            if(MapCacheUtil.lock(publishInfoVO.getId() + EntityTypeEnum.PUBLISH_INFO.getCode())) {
                publishInfoService.cancel(publishInfoDomain);
                response.setSuccess(true);
                response.setMessage("取消成功!");
                response.setResult(publishInfoVO);
            }else {
                throw new BusinessException("正在操作中，请稍后再试!");
            }
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"取消发布信息失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("取消失败，请稍后再试");
            logger.error(LOG_PREFIX+"取消发布信息失败,失败原因",e2);
        }finally {
            MapCacheUtil.unlock(publishInfoVO.getId() + EntityTypeEnum.PUBLISH_INFO.getCode());
        }
        logger.info("结束取消发布信息，返回数据:{}", JSON.toJSONString(publishInfoVO));
        return  response;

    }


    @RequestMapping(value = "/querySignUpPublishedInfoList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="查询报名发布信息")
    public BaseResponse querySignUpPublishedInfoList(HttpServletRequest request, PublishInfoVO publishInfoVO, QueryPage queryPage){
        logger.info("开始查询报名的发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoVO> response=new BaseResponse();

        try {
            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                publishInfoVO.setApplicantId((Long)memberId);
            }

            PublishInfoChecker.checkPageQuery(queryPage);
            publishInfoVO.setQueryPage(queryPage);
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            List<PublishInfoDO> publishInfoDOList=publishInfoService.querySignUpPublishedInfoList(publishInfoDomain);
            List<PublishInfoVO> publishInfoVOList=new ArrayList<>(publishInfoDOList.size());
            if(!CollectionUtils.isEmpty(publishInfoDOList)){
                for(PublishInfoDO publishInfoDO:publishInfoDOList){
                    PublishInfoVO publishInfoVO1=new PublishInfoVO();
                    BeanConverterUtil.copyProperties(publishInfoVO1, publishInfoDO);
                    if(null!=publishInfoDO.getCreateTime()){
                        publishInfoVO1.setCreateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(publishInfoDO.getCreateTime()));
                    }
                    if(null!=publishInfoDO.getUpdateTime()){
                        publishInfoVO1.setUpdateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(publishInfoDO.getUpdateTime()));
                    }

                    publishInfoVOList.add(publishInfoVO1);
                }
            }

            response.setSuccess(true);
            response.setMessage("查询成功!");
            response.setTotalRecord(publishInfoVOList.size());
            response.setQueryPage(queryPage);
            response.setResultList(publishInfoVOList);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询发布信息失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("查询发布信息失败，请稍后再试");
            logger.error(LOG_PREFIX+"插入发布信息失败,失败原因",e2);
        }
        logger.info("结束查询发布信息，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }



    @RequestMapping(value = "/publishedInfoList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="查询发布信息")
    public BaseResponse publishedInfoList( PublishInfoVO publishInfoVO, QueryPage queryPage){
        logger.info("开始查询发布信息，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoVO> response=new BaseResponse();

        try {
            PublishInfoChecker.checkPageQuery(queryPage);
            publishInfoVO.setQueryPage(queryPage);
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);
            List<PublishInfoDO> publishInfoDOList=publishInfoService.applyPublishInfoList(publishInfoDomain);
            List<PublishInfoVO> publishInfoVOList=new ArrayList<>(publishInfoDOList.size());
            if(!CollectionUtils.isEmpty(publishInfoDOList)){
                for(PublishInfoDO publishInfoDO:publishInfoDOList){
                    PublishInfoVO publishInfoVO1=new PublishInfoVO();
                    BeanConverterUtil.copyProperties(publishInfoVO1, publishInfoDO);
                    if(null!=publishInfoDO.getCreateTime()){
                        publishInfoVO1.setCreateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(publishInfoDO.getCreateTime()));
                    }
                    if(null!=publishInfoDO.getUpdateTime()){
                        publishInfoVO1.setUpdateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(publishInfoDO.getUpdateTime()));
                    }

                    publishInfoVOList.add(publishInfoVO1);
                }
            }

            response.setSuccess(true);
            response.setMessage("查询成功!");
            response.setTotalRecord(publishInfoVOList.size());
            response.setQueryPage(queryPage);
            response.setResultList(publishInfoVOList);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询发布信息失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("查询发布信息失败，请稍后再试");
            logger.error(LOG_PREFIX+"插入发布信息失败,失败原因",e2);
        }
        logger.info("结束查询发布信息，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }


    @RequestMapping(value = "/queryPublishInfoDetailById.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="查询发布信息详情")
    public BaseResponse queryPublishInfoDetailById( PublishInfoVO publishInfoVO){
        logger.info("开始查询发布信息详情，请求参数:{}", JSON.toJSONString(publishInfoVO));
        BaseResponse<PublishInfoDO> response=new BaseResponse();

        try {
            PublishInfoChecker.checkId(publishInfoVO.getId());
            PublishInfoDomain publishInfoDomain= ModelConvert.publishInfoVO2PublishInfoDomain(publishInfoVO);

            PublishInfoDO publishInfoDO=publishInfoService.queryPublishInfoDetailById(publishInfoDomain);
            PublishInfoVO publishInfoVO1=new PublishInfoVO();
            BeanConverterUtil.copyProperties(publishInfoVO1, publishInfoDO);
            if(null!=publishInfoDO.getCreateTime()){
                publishInfoVO1.setCreateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(publishInfoDO.getCreateTime()));
            }
            if(null!=publishInfoDO.getUpdateTime()){
                publishInfoVO1.setUpdateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(publishInfoDO.getUpdateTime()));
            }

            response.setSuccess(true);
            response.setMessage("查询成功!");
            response.setResult(publishInfoDO);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询发布信息详情失败，失败原因：",e1);
            response.setSuccess(false);
            response.setMessage(e1.getMessage());
        }catch (Exception e2){
            response.setSuccess(false);
            response.setMessage("查询详情失败，请稍后再试");
            logger.error(LOG_PREFIX+"查询发布信息详情失败,失败原因",e2);
        }
        logger.info("查询插入发布信息详情，返回数据:{}", JSON.toJSONString(response));
        return  response;

    }
}